package com.ruoyi.charge.utils;

/**
 * @author laifeng
 * @version 1.0
 * @date 2025/8/5 23:17
 */

public class YkcHexUtil {
    /**
     * 支持任意长度 Hex，自动右对齐补 0
     *
     * @param hex          内容
     * @param targetLength 字节数
     * @return
     */
    public static byte[] hexStringToPaddedBytes(String hex, int targetLength) {
        byte[] bytes = cn.hutool.core.util.HexUtil.decodeHex(hex); // Hex string → byte[]
        if (bytes.length > targetLength) {
            throw new IllegalArgumentException("Hex string too long: " + hex);
        }
        byte[] result = new byte[targetLength];
        // 右对齐：从右边开始放
        System.arraycopy(bytes, 0, result, targetLength - bytes.length, bytes.length);
        return result;
    }

    /**
     * 支持任意长度 Hex，自动左对齐补 0
     */
    public static byte[] hexStringToPaddedBytesLeft(String hex, int targetLength) {
        byte[] bytes = cn.hutool.core.util.HexUtil.decodeHex(hex);
        if (bytes.length > targetLength) {
            throw new IllegalArgumentException("Hex string too long: " + hex);
        }
        byte[] result = new byte[targetLength];
        System.arraycopy(bytes, 0, result, 0, bytes.length);
        return result;
    }
}
